package com.witdata.common.service.community.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.witdata.common.domain.Status;
import com.witdata.common.domain.dto.ArticleLikeDto;
import com.witdata.common.exception.GlobalException;
import com.witdata.common.mapper.ArticleLikeMapper;
import com.witdata.common.service.community.ArticleLikeService;
import com.witdata.common.util.IdUtils;
import com.witdata.mysql.base.service.ArticleLikeBaseService;
import com.witdata.mysql.base.service.CommunityArticleBaseService;
import com.witdata.mysql.domain.entity.TArticleLike;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author LiuQi
 */
@Service
@RequiredArgsConstructor
public class ArticleLikeServiceImpl implements ArticleLikeService {
    private final ArticleLikeBaseService articleLikeBaseService;
    private final CommunityArticleBaseService communityArticleBaseService;
    private final IdUtils idUtils;
    @Override
    public void likeArticle(Long articleId) {
        Long userId = idUtils.getUserIdByRequest();
        //查询文章是否存在
        if (!communityArticleBaseService.exists(new QueryWrapper().eq("id", articleId))) {
            throw new GlobalException(Status.ARTICLENOTFOUND);
        }
        if (articleLikeBaseService.exists(new QueryWrapper().eq("article_id", articleId).eq("user_id", userId))) {
            throw new GlobalException(Status.LIKEERROR);
        }
        articleLikeBaseService.save(TArticleLike.builder()
                .id(IdUtils.createId())
                .articleId(articleId)
                .userId(userId)
                .created(LocalDateTime.now())
                .build());
    }

    @Override
    public void unlikeArticle(Long articleId) {
        Long userId = idUtils.getUserIdByRequest();
        if (!articleLikeBaseService.exists(new QueryWrapper().eq("article_id", articleId).eq("user_id", userId))) {
            throw new GlobalException(Status.UNLIKEERROR);
        }
        boolean remove = articleLikeBaseService.remove(new QueryWrapper().eq("article_id", articleId).eq("user_id", userId));
        if (!remove) throw new GlobalException(Status.DELETEERROR);
    }

    @Override
    public List<ArticleLikeDto> getArticleLikeList() {
        Long userId = idUtils.getUserIdByRequest();
        List<TArticleLike> tArticleLikeList = articleLikeBaseService.list(new QueryWrapper().eq("user_id", userId));
        return ArticleLikeMapper.INSTANCE.toArticleLikeDtoList(tArticleLikeList);
    }
}
